package com.tzinfo.tzt.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.galhttprequest.GalHttpRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tzinfo.data.TztData;
import com.tzinfo.tzb.domain.DefaultResult;
import com.tzinfo.tzb.domain.DiaryList;
import com.tzinfo.tzb.util.FileConfig;
import com.tzinfo.tzb.util.HttpTools;
import com.tzinfo.tzt.R;
import com.tzinfo.tzt.util.HttpUtils;
import com.tzinfo.tzt.util.ResultMessage_NoData;
import com.yxw.util.OutLog;
import com.yxw.view.YXWProgressDialog;
import com.yxw.view.util.ResFinder;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class ReleaseFragment extends Fragment {

    private Context context;
    private ImageView img_riji, img_delete, img_touxiang;

    private AlertDialog dlg;
    protected Dialog dialog;
    private Object imagePath = null;
    DefaultResult result = null;
    public DiaryList.DiaryData diaryData = null;
    private DiaryList diaryList;
    private boolean isPub = true;
    private int flag = 0;
    private String pid;
    public ReleaseSuccess releaseGo;

    ImageLoader imageLoader;

    public ReleaseFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (TztData.isUserLogin) {
            View view = inflater.inflate(R.layout.tzt_fragment_release, container, false);
            final EditText tv_subject = (EditText) view.findViewById(R.id.fragment_release_subject);
            final EditText tv_message = (EditText) view.findViewById(R.id.fragment_release_message);
            img_riji = (ImageView) view.findViewById(R.id.img_riji);
            img_riji.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showAddImageDialog(v);
                }
            });
            img_delete = (ImageView) view.findViewById(R.id.img_delete);
            img_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onDeleteImage(v);
                }
            });
            img_touxiang = (ImageView) view.findViewById(R.id.img_touxiang);


            TextView tv_up = (TextView) view.findViewById(R.id.fragment_release_up);
            tv_up.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //提交帖子数据

                    new UpPostTask().execute(tv_subject.getText().toString(), tv_message.getText().toString());
                }
            });
            return view;
        } else
            return inflater.inflate(R.layout.fragment_user, container, false);
    }

    // TODO: Rename method, update argument and hook method into UI event


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        context = activity;
        releaseGo = (ReleaseSuccess) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }

    public class UpPostTask extends AsyncTask<String, Void, ResultMessage_NoData> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected ResultMessage_NoData doInBackground(String... params) {
            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
            pairs.add(new BasicNameValuePair("fid", "21"));
            pairs.add(new BasicNameValuePair("subject", params[0]));
            pairs.add(new BasicNameValuePair("message", params[1]));

            pairs.add(new BasicNameValuePair("sessionid", TztData.userInfo.getData().getSessionID()));
            String GetDataUrl = "http://tzt.tzinfo.net/mob/api/ForumthreadPub.ashx";
            String DataString = HttpUtils.doPostMethod(GetDataUrl, pairs);
            Gson gson = new Gson();
            ResultMessage_NoData result = gson.fromJson(DataString, ResultMessage_NoData.class);
            return result;
        }

        @Override
        protected void onPostExecute(ResultMessage_NoData resultMessage_noData) {
            super.onPostExecute(resultMessage_noData);
            if (resultMessage_noData==null){
                Toast.makeText(context, "发帖失败，请重试", Toast.LENGTH_SHORT).show();
            }
            else if (resultMessage_noData.getSuccess()) {
                Toast.makeText(context, "发帖成功", Toast.LENGTH_SHORT).show();
                pid = resultMessage_noData.getErrorMsg();

                if (imagePath instanceof String) {
                    dialog = new YXWProgressDialog(context).createDialog("开始上传图片");
                    dialog.show();
                    new Thread(upLoadImageRun).start();
                } else {
                    releaseGo.go();
                }
            }
        }
    }

    public interface ReleaseSuccess {
        public void go();
    }

    public void showAddImageDialog(View v) {
        if (!(imagePath instanceof DiaryList.DiaryData.DiaryPhoto)) {
            final CharSequence[] items = {"相册", "拍照", "取消"};

            dlg = new AlertDialog.Builder(context).setTitle("选择照片")
                    .setItems(items, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            // 这里item是根据选择的方式，
                            // 在items数组里面定义了两种方式，拍照的下标为1所以就调用拍照方法
                            if (which == 0) {
                                Intent getImage = new Intent(
                                        Intent.ACTION_GET_CONTENT);
                                getImage.addCategory(Intent.CATEGORY_OPENABLE);
                                getImage.setType("image/*");
                                startActivityForResult(getImage, 2);
                            } else if (which == 1) {
                                Intent getImageByCamera = new Intent(
                                        "android.media.action.IMAGE_CAPTURE");
                                File tempFile = new File(FileConfig.IMAGE_PATH);
                                if (!tempFile.isDirectory()) {
                                    tempFile.mkdirs();
                                }
                                FileConfig.IMAGE_NAME = FileConfig
                                        .getRandomJpgName();
                                Uri imageUri = Uri.fromFile(new File(
                                        FileConfig.IMAGE_PATH,
                                        FileConfig.IMAGE_NAME));
                                // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
                                getImageByCamera.putExtra(
                                        MediaStore.EXTRA_OUTPUT, imageUri);
                                startActivityForResult(getImageByCamera, 3);
                            } else {
                                dlg.dismiss();
                            }
                        }
                    }).create();
            dlg.show();
        }
    }

    public void onDeleteImage(View v) {
        new AlertDialog.Builder(context)
                .setTitle("友情提醒")
                .setMessage("您确定要删除这张照片吗？")
                .setPositiveButton("确	定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                deleteImage(imagePath);
                            }
                        })
                .setNegativeButton("取	消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                            }
                        }).show();
    }

    private void deleteImage(Object object) {
        if (object instanceof String) {
            dialog.show();
            img_riji.setImageResource(R.drawable.tzb_image_add);
            img_delete.setVisibility(View.GONE);
            imagePath = null;
            Toast.makeText(context, "已删除图片！", Toast.LENGTH_LONG).show();
            dialog.dismiss();
        } else {// 网络的删除需要通过HTTP请求
            dialog.show();
            DiaryList.DiaryData.DiaryPhoto diaryPhoto = (DiaryList.DiaryData.DiaryPhoto) object;
            GalHttpRequest galHttpRequest = new GalHttpRequest(
                    context);
            String url = ResFinder.getResString(context,
                    "R.string.tzb_url_DiaryPhotoDelete")
                    + "?sessionid="
                    + TztData.userInfo.getData().getSessionID()
                    + "&diaryid="
                    + diaryData.getId() + "&photoid=" + diaryPhoto.getId();
            OutLog.LogE("yxw", "delete:" + url);
            galHttpRequest.setCacheEnable(false);
            galHttpRequest.setURL(url);
            galHttpRequest
                    .startAsynRequestString(new GalHttpRequest.GalHttpLoadTextCallBack() {

                        @Override
                        public void textLoaded(String arg0) {
                            DefaultResult result = null;
                            Gson gson = new Gson();
                            java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                            }.getType();
                            result = gson.fromJson(arg0, type);
                            OutLog.LogE("yxw", "result:" + result.toString());
                            if (result.isSuccess()) {
                                img_riji.setImageResource(R.drawable.tzb_image_add);
                                img_delete.setVisibility(View.GONE);
                                imagePath = null;
                                Toast.makeText(context,
                                        "已删除图片！", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(context,
                                        result.getMsg(), Toast.LENGTH_SHORT).show();
                            }
                            dialog.dismiss();
                        }
                    });
        }

    }

    Runnable upLoadImageRun = new Runnable() {

        @Override
        public void run() {
            Message message = handler.obtainMessage();
            String url = ResFinder.getResString(context,
                    "R.string.tzb_url_attachment_Add")
                    + "?sessionid="
                    + TztData.userInfo.getData().getSessionID()
                    + "&pid=" + pid;
            OutLog.LogE("yxw", "add:" + url);
            String path = (String) imagePath;
            if (path != null) {
                String jsonString = HttpTools.uploadImage(url, path);
                Log.e("jsonImage", jsonString);
                DefaultResult result = null;
                Gson gson = new Gson();
                java.lang.reflect.Type type = new TypeToken<DefaultResult>() {
                }.getType();
                result = gson.fromJson(jsonString, type);
                if (result.isSuccess()) {
                    message.arg1 = 1;
                } else {
                    message.arg1 = -1;
                }
            }
            handler.sendMessage(message);
        }
    };
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 1:
                    dialog.dismiss();
                    releaseGo.go();
                    //        goback(null);
                    break;
                case -1:
                    dialog.dismiss();
                    releaseGo.go();
                    Toast.makeText(context, "图片上传失败！",
                            Toast.LENGTH_SHORT).show();
                    //       goback(null);
                    break;
            }
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        BitmapFactory.Options option = null;
        switch (requestCode) {
            case 2:
                if (data != null) {
                    img_delete.setVisibility(View.VISIBLE);
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};

                    Cursor cursor = context.getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    String picturePath = cursor.getString(columnIndex);
                    cursor.close();
                    // 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
                    option = new BitmapFactory.Options();
                    option.inSampleSize = 5;
                    imagePath = picturePath;
                    img_riji.setImageBitmap(BitmapFactory.decodeFile(picturePath,
                            option));
                }
                break;
            case 3:
                img_delete.setVisibility(View.VISIBLE);
                // 图片的压缩显示，如果不压缩，当图片太大时会导致内存溢出 或者应用很卡
                option = new BitmapFactory.Options();
                String path = FileConfig.IMAGE_PATH + "/" + FileConfig.IMAGE_NAME;
                option.inSampleSize = 5;
                imagePath = path;
                img_riji.setImageBitmap(BitmapFactory.decodeFile(path, option));
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
